<?php
declare(strict_types=1);
namespace cms\exam\admin\api_controller;

use cms\exam\request\AppFormRequest;
use cms\exam\request\TopicFormRequest;
use cms\exam\service\AppService;
use cms\exam\service\TopicGroupService;
use cms\exam\service\TopicService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\PostMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Psr\Http\Message\ResponseInterface;

/**
 * Class AppController
 * @package cms\exam\admin\api_controller
 * @Controller(prefix="api/exam/admin_topic")
 */
class TopicController extends CommonController
{
    /**
     * @Inject()
     * @var TopicService
     */
    protected TopicService $topicService;

    /**
     * @Inject()
     * @var TopicGroupService
     */
    protected TopicGroupService $topicGroupService;

    /**
     * @param TopicFormRequest $request
     * @return ResponseInterface
     * @PostMapping(path="create")
     */
    public function create(TopicFormRequest $request): ResponseInterface
    {
        $app = $this->_getApp(true);
        $form_data = $request->validated();
        // 题型
        $type = $this->topicService->readSetting('topic')->get('type');
        if (!array_key_exists($form_data['type'], $type)) {
            return $this->error('题型设置错误');
        }
        // 判断题目
        $name = cms_text($form_data['content']['subject'], 100);
        if (!$name) {
            return $this->error('请输入题目');
        }
        $form_data['name'] = $name;
        $form_data['app_id'] = $app->id;
        $result = $this->topicService->model->create($form_data);
        return $this->success('请求成功', $result);
    }

    /**
     * @param TopicFormRequest $request
     * @return ResponseInterface
     * @PostMapping(path="update")
     */
    public function update(TopicFormRequest $request): ResponseInterface
    {
        $form_data = $request->validated();
        $id = (int) $this->request->input('id', 0);
        $data = $this->topicService->getDataById($id, true);
        $data->fill($form_data);
        $data->save();
        return $this->success('请求成功', $data);
    }


    /**
     * @return ResponseInterface
     * @RequestMapping(path="retrieve")
     */
    public function retrieve(): ResponseInterface
    {
        $app = $this->_getApp(true);
        $where = [
            ['app_id', '=', $app->id]
        ];
        $group_id = (int) $this->request->input('group_id', 0);
        $group = $this->topicGroupService->getDataById($group_id);
        if ($group) {
            $where[] = ['group_id', '=', $group_id];
        }

        $result = $this->topicService->model->where($where)->paginate(10);
        return $this->success('请求成功', [
            'total' => $result->total(),
            'items' => $result->items()
        ]);
    }
}